import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast';

const Util = require("../../utils/utils")

var myUploadFile = Util.wxPromisify(wx.uploadFile);

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgList: [],
    StatusBar: 20,
    CustomBar: 60,
    show: false,
    content: "",
    list: null,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 拉取文章
    this.getList();
  },

  // 发布文章
  publish() {

    let user = null;
    try {
      user = wx.getStorageSync('user');
    } catch (error) {
      user = null;
    }
    if (user == null || user == "") {
      Toast.fail('请先登录');
      return;
    }
    let {
      imgList,
      content
    } = this.data;

    // 提示用户正在发送中，因为网络问题，所以有点慢
    const toast = Toast.loading({
      duration: 0, // 持续展示 toast
      message: '正在发布中...',
      forbidClick: true,
    });

    var ok = 0;
    const timer = setInterval(() => {
      if (ok == 2) {
        clearInterval(timer);
        Toast.clear();
      } else if (ok == 1) {
        toast.setData({
          message: "已上传oss",
        });
      }
    }, 500);


    var that = this;

    // 1.上传图片至 oss 服务器，这里选七牛云
    let url = `${app.globalData.baseURL}/api/sys/oss/upload?token=${app.globalData.token}`;
    new Promise((resolve, reject) => {
      var count = 0;
      var ans = [];
      imgList.forEach(e => {
        // 图片上传
        wx.uploadFile({
          filePath: e,
          name: 'file',
          url,
          success(res) {
            count++;
            // console.log(res);
            /**
             * 下面是服务器传回来的，狗屁玩意儿吧 emm
             * data:"{"msg":"success","code":0,"url":"http://qsq1ikn4e.hn-bkt.clouddn.com/upload/20210507/653fbc39b23248ea9f49985b591e5938.png"}"
             * 
             */
            let u = res.data.slice(27).slice(6).slice(0, -2);
            // console.log(u);
            ans.push(u);
            if (count == imgList.length) {
              ok = 1;
              // console.log(ans);
              resolve(ans);
            }
          }
        })
      })
    }).then(prev => {

      // 2.将数据传输到后端
      // 2.1 先将文章保存到服务器， 拿到文章id
      url = `${app.globalData.baseURL}/api/content/cmsinterview/save`;
      wx.request({
        url,
        method: "POST",
        data: {
          memberId: user.id,
          content
        },
        success(res) {
          // 将文章id加到图片对象中
          let lists = [];
          prev.forEach(url => {
            lists.push({
              "interviewId": res.data.id,
              "imgUrl": url
            })
          });
          // // 2.2 保存文章图片
          wx.request({
            url: `${app.globalData.baseURL}/api/content/cmsinterviewimg/saveBatch`,
            method: "POST",
            data: lists,
            success(last) {
              // console.log(last);
              ok = 2;
              that.setData({
                show: false,
                content: "",
                imgList: [],
              })
              // 拉取文章
              that.getList();
            }
          })
        }
      })
    })

  },

  // 拉取文章
  getList() {
    Toast.loading({
      message: '加载中...',
      forbidClick: true,
    });
    // 正在拉取最新文章
    let that = this;
    let url = `${app.globalData.baseURL}/api/content/cmsinterview/list?page=1&limit=30`;

    // 1.请求文章基本信息
    new Promise((resolve, reject) => {
      wx.request({
        url,
        success(res1) {
          let vlist = res1.data.page.list;
          resolve(vlist);
        },
      })
    }).then(vlist => {
      // 2.请求图片url
      new Promise((resolve, reject) => {
        var num = 0;
        vlist.forEach((e, i) => {
          vlist[i].createTime = Util.formatTime(new Date(vlist[i].createTime))
          // 获取图片
          wx.request({
            url: `${app.globalData.baseURL}/api/content/cmsinterviewimg/article/${e.id}`,
            success(res2) {
              vlist[i]["imgeLists"] = res2.data.imgeLists;
              num++;
              if (num == vlist.length) {
                resolve(vlist);
              }
            }
          });
        })
      }).then(vlist => {
        // 3.获取作者信息
        new Promise((resolve, reject) => {
          var num = 0;
          vlist.forEach((e, i) => {
            wx.request({
              url: `${app.globalData.baseURL}/api/member/member/info/${e.memberId}`,
              success(res3) {
                vlist[i]["username"] = res3.data.umsMember.nickname;
                num++;
                if (num == vlist.length) {
                  resolve(vlist);
                }
              }
            });
          })
        }).then(vlist => {
          // 4.排序后赋值
          // console.log(vlist);
          // 后添加的日期比较靠后....
          vlist = vlist.reverse();

          //停止下拉刷新
          wx.stopPullDownRefresh();

          that.setData({
            vlist
          })
        })
      });

    });

  },



  /** 以下三个是图片操作 */
  ChooseImage() {
    wx.chooseImage({
      count: 4, //默认9
      sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album'], //从相册选择
      success: (res) => {
        // console.log(res.tempFilePaths);
        if (this.data.imgList.length != 0) {
          this.setData({
            imgList: this.data.imgList.concat(res.tempFilePaths)
          })
        } else {
          this.setData({
            imgList: res.tempFilePaths
          })
        }
      }
    });
  },
  ViewImage(e) {
    wx.previewImage({
      urls: this.data.imgList,
      current: e.currentTarget.dataset.url
    });
  },
  DelImg(e) {
    wx.showModal({
      title: '架构师',
      content: '确定要删除这张图片吗？',
      cancelText: '再想想',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
          this.data.imgList.splice(e.currentTarget.dataset.index, 1);
          this.setData({
            imgList: this.data.imgList
          })
        }
      }
    })
  },

  isCard(e) {
    this.setData({
      isCard: e.detail.value
    })
  },

  onClose() {
    this.setData({
      show: false
    })
  },

  toPublish() {
    this.setData({
      show: true
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  //刷新
  onRefresh() {
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading();
    //需主动调用 api 关闭
    this.getList();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.onRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 设置自定义tabbar，active显示属性
  onShow() {
    // console.log("主页tab");
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        active: 2
      })
    }
  }
})